

********************************************************************************
*This file calculates MMF LPI
********************************************************************************

*-------------------------------------------------------------------------------------------------*
* Extrapolate the illiquidity measures for ag_deb, ag_mbscmo, cash, moabs, com_loan ,mm, and muni
*-------------------------------------------------------------------------------------------------*
*set working directory
global folder ".."


use "../data_input/data_mmf.dta", clear

g awgt_bond_mean = .9969825 //based on the bond mutual fund merged sample
g awgt_bond_ORG0_mean = .9390159 //based on the bond mutual fund merged sample
* Use the ratio between haircut and IRC of corporate bonds to do the extrapolation
local list cash treas mm
foreach x of local list{
	gen awgt_`x'= 1 - (1 - awgt_`x'_ORG0) * (1 - awgt_bond_mean) / (1 - awgt_bond_ORG0_mean)
}

drop awgt_bond_mean awgt_bond_ORG0_mean
local list cash treas mm
foreach x of local list {
	drop awgt_`x'_ORG0
}


local list cash treas mm
foreach x of local list {
g `x'_liq_value_pct = sa_mf_`x'*awgt_`x'
}
* generate cumulative liquidation value (the liquidation value upto J asset)
g temp = 0
local list cash treas mm
foreach x of local list {
g `x'_liq_value_pct_cum = temp + `x'_liq_value_pct
replace temp = temp +  `x'_liq_value_pct
}
rename temp liq_value_pct


replace liq_value_pct=1 if liq_value_pct>1&liq_value_pct!=.


/* generate lpi without swing pricing */
gen lpi = 0 if -flow>liq_value_pct
replace lpi = 1/liq_value_pct-1 if -flow<liq_value_pct

g expected_lti = lpi // create the same variable names
gen expected_total_lti=expected_lti*assetstotal 

sum expected_lti, d


* generate cumulative portfolio weight (the portfolio weight upto J asset)
g temp_weight = 0
local list cash treas mm
foreach x of local list {
g `x'_weight = sa_mf_`x'
g `x'_weight_cum = temp_weight + `x'_weight 
replace temp_weight = temp_weight + `x'_weight 
}

* keep outflow only
g flow_trunc = flow
replace flow_trunc = 0 if flow>0
replace flow_trunc = -1 if flow<-1


* generate lpi without raw outflows
g lpi_sp= .

local list cash treas mm
foreach x of local list {
replace lpi_sp = (`x'_liq_value_pct_cum-`x'_liq_value_pct+ (1-(`x'_weight_cum-`x'_weight))*awgt_`x')/liq_value_pct/(1-(1-(-flow_trunc))*(1-awgt_`x'))-1 if -flow_trunc>=(`x'_liq_value_pct_cum-`x'_liq_value_pct)/((`x'_liq_value_pct_cum-`x'_liq_value_pct)+(1-(`x'_weight_cum-`x'_weight)))
}


sum lpi_sp, d
replace lpi_sp=0 if lpi_sp<0

g expected_lti_sp = lpi_sp // create the same variable names
gen expected_total_lti_sp=expected_lti_sp*assetstotal 

sum expected_lti*
sum expected_lti*,d

save "../data_intermediate/mmf_ltisample_haircutrobust_new.dta", replace
